const LOGIN_ERROR = '40029' //登录失败
const LOGIN_EXPIRE = '401' //登录过期
const BALANCE_NOT_ENOUGH = '11001' //余额不足
const regeneratorRuntime = require('../vendor/regenerator-runtime.js')
const co = require('../vendor/co.js')
const loginUrl = "rest/member/login.do"
const infoConfigUrl = "rest/config/queryByList.do"; //请求根 地址

const version = '1.1'
const device = 'program'
let retry = 0

let baseUrl = "https://www.cheyouyou.net/"; //请求根 地址


function isJSON(obj) {
  return typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}

function doRequest(config) {
  const app = getApp()
  return co(function* () {
    //sid
    let token = wx.getStorageSync('token')
    let pre_invite_code = wx.getStorageSync('pre_invite_code')
    if (!token) {
      //wx login
      let loginRes = yield app.toPromise(wx.login)
      let loginInfo = yield app.toPromise(wx.request, {
        url: baseUrl + loginUrl,
        method: "POST",
        data: JSON.stringify({
          "token": '',
          "version": version,
          "device": device,
          "data": JSON.stringify({
            code: loginRes.code,
            invite: pre_invite_code
          })
        })
      })
      if (loginInfo.data.code == "200") {
        let data = loginInfo.data.obj
        wx.setStorage({
          key: 'token',
          data: data.token
        })
        wx.setStorage({
          key: 'mid',
          data: data.id,
        })
        token = data.token
        data.name && data.image && wx.setStorage({
          key: 'user',
          data: {
            name: data.name,
            image: data.image,
          }
        })
        data.mobile && wx.setStorage({
          key: 'mobile',
          data: data.mobile,
        })
      } else {
        wx.hideLoading()
        return Promise.reject({
          message: '登录失败',
          code: LOGIN_ERROR
        })
      }
    }
    
    let infoConfig = yield app.toPromise(wx.request, {
      url: baseUrl + infoConfigUrl,
      method: "POST",
      data: JSON.stringify({
        "token": token,
        "version": version,
        "device": device,
      })
    })

    wx.setStorageSync('settings', infoConfig.data.obj)

    let cfg = Object.assign({}, config)
    if (!cfg.data) {
      cfg.data = ''
    }
    cfg.data = JSON.stringify({
      token: token,
      version: version,
      device: device,
      data: isJSON(cfg.data) ? JSON.stringify(cfg.data) : cfg.data
    })
    let res = yield app.toPromise(wx.request, cfg)

    if (res.data.code != "200") {
      //请求错误
      wx.hideLoading()
      return Promise.reject(res.data)
    }
    return res.data
  })
}

function req(config) {
  let retry = 5
  config = Object.assign({
    showMsg: true
  }, config);

  return doRequest(config).then(res => {
    return Promise.resolve(res)
  }).catch(err => {
    if (err.code == LOGIN_EXPIRE) {
      //登录过期
      retry--
      if (retry > 0) {
        wx.removeStorageSync('token')
        return doRequest(config)
      }
      return Promise.reject({
        message: '请求失败',
        code: -1
      })
    }
    if (err.code == LOGIN_ERROR) {
      wx.showModal({
        title: '提示',
        content: '登录失败，请删除小程序后重试',
        showCancel: false,
        confirmColor: '#4db4ff',
        success: res => {
          wx.removeStorage({
            key: 'token',
            success: function (res) { },
          })
          res.confirm && wx.navigateBack({

          })
        }
      })
    }
    if (err.code == BALANCE_NOT_ENOUGH) {
      wx.showModal({
        title: '提示',
        content: '余额不足,请充值',
        showCancel: false,
        confirmColor: '#4db4ff',
        success: res => {
          res.confirm && wx.navigateTo({
            url: '/pages/common/recharge',
          })
        }
      })
    }
    err.msg && config.showMsg && getApp().wxToast.error(err.msg)
    return Promise.reject(err)
  })
}
module.exports = {
  get: function (url, config = {}) {
    config.url = (config.baseUrl || baseUrl) + url
    config.method = "GET"
    return req(config)
  },
  post: function (url, config = {}) {
    config.url = (config.baseUrl || baseUrl) + url
    config.method = "POST"
    return req(config)
  },
  getBaseUrl() {
    return baseUrl
  }

}